<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import api from '../api'

// 统一图表初始化函数
const initChart = async (elementId, optionRef, fetchData) => {
  await fetchData()
  const container = document.getElementById(elementId)
  if (!container) {
    console.error(`容器 #${elementId} 不存在`)
    return
  }

  const chart = echarts.init(container)
  chart.setOption(optionRef.value)

  // 响应式调整
  const resizeHandler = () => chart.resize()
  window.addEventListener('resize', resizeHandler)

  // 组件卸载时移除监听器
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler)
    chart.dispose()
  })
}

// ================= 图表配置 =================
// 影厅使用趋势（折线图）
const optionA = ref({
  title: {
    text: '影厅使用趋势',
    left: 'center',
    textStyle: { fontSize: 18, fontWeight: 'bold', color: '#2c3e50' },
    padding: [10, 0]
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderColor: '#e6e6e6',
    borderWidth: 1,
    padding: [10, 15],
    textStyle: { color: '#333', fontSize: 14 },
    extraCssText: 'box-shadow: 0 6px 16px rgba(0,0,0,0.1); border-radius: 8px;',
    formatter: params => `${params[0].name}<br/>${params[0].marker} ${params[0].seriesName}: ${params[0].value}场次`
  },
  grid: { left: '3%', right: '4%', bottom: '10%', top: '极狐15%', containLabel: true },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: { rotate: 30, fontSize: 12, color: '#666' },
    axisLine: { lineStyle: { color: '#dcdee0' } },
    axisTick: { alignWithLabel: true }
  },
  yAxis: {
    type: 'value',
    name: '使用场次',
    nameTextStyle: { fontSize: 12, padding: [0, 0, 0, 10] },
    axisLabel: { fontSize: 12, color: '#666' },
    splitLine: { lineStyle: { type: 'dashed', color: '#f0f0f0' } }
  },
  series: [{
    name: '使用次数',
    type: 'line',
    data: [],
    smooth: true,
    symbol: 'circle',
    symbolSize: 8,
    itemStyle: { color: '#5470c6' },
    lineStyle: {
      width: 3,
      color: '#5470c6',
      shadowColor: 'rgba(84, 112, 198, 0.3)',
      shadowBlur: 10,
      shadowOffsetY: 5
    },
    areaStyle: {
      color: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
          { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
          { offset: 1, color: 'rgba(84, 112, 198, 0.05)' }
        ]
      }
    },
    animation: true,
    animationDuration: 1500,
    animationEasing: 'cubicOut'
  }]
})

// 电影类型分布（饼图）
const optionB = ref({
  title: {
    text: '电影类型分布',
    subtext: '各类电影数量占比详情',
    left: 'left',
    textStyle: { fontSize: 18, fontWeight: 'bold', color: '#2c3e50' },
    subtextStyle: { fontSize: 14, color: '#7f8c8d' },
    top: 10
  },
  tooltip: {
    trigger: 'item',
    formatter: '<b>{b}</b>: {极狐c}个 ({d}%)',
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderColor: '#e6e6e6',
    borderWidth: 1,
    padding: [12, 15],
    textStyle: { color: '#333', fontSize: 14 },
    extraCssText: 'box-shadow: 0 6px 16px rgba(0,0,0,0.1); border-radius: 8px;'
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: '5%',
    top: '15%',
    bottom: '15%',
    itemGap: 12,
    icon: 'circle',
    textStyle: { fontSize: 12, fontWeight: 'normal', color: '#555' },
    pageIconColor: '#409eff',
    pageTextStyle: { color: '#888' },
    formatter: name => {
      const dataItem = optionB.value.series[0].data.find(item => item.name === name)
      return `${name}: ${dataItem?.value || ''}个`
    }
  },
  color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'],
  series: [{
    name: '影厅类型',
    type: 'pie',
    radius: ['38%', '60%'],
    center: ['38%', '52%'],
    avoidLabelOverlap: true,
    minAngle: 8,
    itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
    label: {
      show: true,
      position: 'inside',
      formatter: '{d}%',
      fontSize: 12,
      fontWeight: 'bold',
      color: '#fff',
      textBorderColor: 'rgba(0,0,0,0.3)',
      textBorderWidth: 1
    },
    labelLine: { show: false },
    emphasis: {
      itemStyle: { shadowBlur: 20, shadowColor: 'rgba(0,0,0,0.2)' },
      label: { show: true, fontSize: 14 }
    },
    data: [],
    animationType: 'scale',
    animationEasing: 'elasticOut',
    animationDelay: idx => Math.random() * 200
  }],
  graphic: [{
    type: 'group',
    left: 'center',
    bottom: 20,
    children: [{
      type: 'text',
      style: {
        text: '数据更新: ' + new Date().toLocaleDateString(),
        fontSize: 12,
        fill: '#999'
      }
    }]
  }]
})

// 影厅座位使用率（柱状图）
const optionC = ref({
  title: {
    text: '影厅座位使用率',
    left: '10px',
    top: '10px',
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold',
      color: '#2c3e50',
      backgroundColor: '#f5f7fa',
      padding: [5, 10],
      borderRadius: 4
    }
  },
  tooltip: {
    trigger: 'axis',
    formatter: '{b}: {c}%',
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderWidth: 1,
    borderColor: '#eee'
  },
  grid: { left: '3%', right: '4%', bottom: '12%', top: '22%', containLabel: true },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: { rotate: 30, fontSize: 12 },
    // 这里修复了字符串未闭合的问题
    axisLine: { lineStyle: { color: '#dcdee0' } }
  },
  yAxis: {
    type: 'value',
    name: '使用率(%)',
    nameTextStyle: { fontSize: 12, padding: [0, 0, 0, 10] },
    min: 0,
    max: 100,
    splitLine: { lineStyle: { type: 'dashed', color: '#f0f0f0' } },
    axisLabel: { margin: 8 }
  },
  series: [{
    name: '使用率',
    type: 'bar',
    data: [],
    barWidth: '60%',
    itemStyle: { color: '#5470C6', borderRadius: [4, 4, 0, 0] },
    label: {
      show: true,
      position: 'top',
      formatter: '{c}%',
      fontSize: 11,
      fontWeight: 'bold'
    }
  }]
})

// 用户性别分布（饼图）
const optionD = ref({
  title: {
    text: '用户性别分布',
    subtext: '影院会员性别比例统计',
    left: 'left',
    textStyle: { fontSize: 18, fontWeight: 'bold', color: '#2c3e50' },
    subtextStyle: { fontSize: 14, color: '#7f8c8d' },
    top: 10
  },
  tooltip: {
    trigger: 'item',
    formatter: '<b>{b}</b>: {c}人 ({d}%)',
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderColor: '#e6e6e6',
    borderWidth: 1,
    padding: [12, 15],
    textStyle: { color: '#333', fontSize: 14 },
    extraCssText: 'box-shadow: 0 6px 16px rgba(0,0,0,0.1); border-radius: 8px;'
  },
  legend: {
    orient: 'horizontal',
    bottom: 10,
    itemGap: 20,
    icon: 'circle',
    textStyle: { fontSize: 12, fontWeight: 'normal', color: '#555' }
  },
  color: ['#5470c6', '#ee6666', '#91cc75'],
  series: [{
    name: '性别分布',
    type: 'pie',
    radius: '65%',
    center: ['50%', '50%'],
    avoidLabelOverlap: true,
    minAngle: 5,
    itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
    label: {
      show: true,
      position: 'outside',
      formatter: '{b}: {d}%',
      fontSize: 12,
      fontWeight: 'bold',
      color: '#555',
      alignTo: 'labelLine',
      bleedMargin: 5
    },
    label极狐Line: { show: true, length: 10, length2: 15, smooth: true },
    emphasis: {
      itemStyle: { shadowBlur: 20, shadowColor: 'rgba(0,0,0,0.2)' },
      label: { show: true, fontSize: 14, fontWeight: 'bold' }
    },
    data: [],
    animationType: 'scale',
    animationEasing: 'elasticOut',
    animationDelay: idx => idx * 150
  }]
})

// 电影上映热度分布（热力图）
const optionE = ref({
  title: {
    text: '电影上映热度分布',
    subtext: '按年份与月份统计',
    left: 'center',
    textStyle: { fontSize: 18, fontWeight: 'bold', color: '#2c3e50' },
    subtextStyle: { fontSize: 14, color: '#7f8c8d' }
  },
  tooltip: {
    trigger: 'item',
    formatter: params => `📅 ${params.value[0]}年${params.value[1] + 1}月<br>🎬 ${params.value[2]}部电影`,
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderColor: '#e6e6e6',
    borderWidth: 1,
    padding: 12,
    textStyle: { color: '#2c3e50', fontSize: 14, fontWeight: 'bold' },
    extraCssText: 'box-shadow: 0 6px 16px rgba(0,0,0,0.1); border-radius: 8px;'
  },
  grid: { top: 80, bottom: 100, left: 70, right: 50 },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: { rotate: 45, fontSize: 12, color: '#34495e', interval: 0 },
    axisLine: { lineStyle: { color: '#bdc3c7' } },
    axisTick: { alignWithLabel: true }
  },
  yAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    axisLabel: { fontSize: 12, color: '#34495e', margin: 10 },
    axisLine: { lineStyle: { color: '#bdc3c7' } },
    splitLine: { show: true, lineStyle: { color: '#f0f0f0', type: 'dashed' } }
  },
  visualMap: {
    min: 0,
    max: 100,
    calculable: true,
    orient: 'vertical',
    right: 15,
    top: 'center',
    itemWidth: 20,
    itemHeight: 150,
    textStyle: { fontSize: 12, color: '#7f8c8d' },
    inRange: { color: ['#5470c6', '#91cc75', '#fac858', '#ee6666'] },
    outOfRange: { color: '#f0f0f0' }
  },
  series: [{
    type: 'heatmap',
    data: [],
    label: {
      show: true,
      color: '#2c3e50',
      fontSize: 11,
      fontWeight: 'bold',
      formatter: params => params.value[2] > 0 ? params.value[2] : ''
    },
    itemStyle: { borderWidth: 1, borderColor: '#fff', borderType: 'solid' },
    emphasis: {
      itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.3)' },
      label: { show: true, fontSize: 12, color: '#e74c3c' }
    },
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  }]
})

// ================= 数据获取函数 =================
async function getChartsA() {
  const result = await api.getChartsA()
  optionA.value.xAxis.data = result.category
  optionA.value.series[0].data = result.hallCount
}

async function getChartsB() {
  const result = await api.getChartsB()
  optionB.value.series[0].data = result.category.map((name, index) => ({
    name,
    value: result.count[index]
  }))
}

async function getChartsC() {
  const result = await api.getChartsC()
  optionC.value.xAxis.data = result.name
  optionC.value.series[0].data = result.num
}

async function getChartsD() {
  const result = await api.getChartsD()
  optionD.value.series[0].data = result.gender.map((name, index) => ({
    name,
    value: result.count[index]
  }))
}

async function getChartsE() {
  const result = await api.getChartsE()
  console.log("热力图原始数据:", result)

  if (!result.year || result.year.length === 0) {
    console.error("热力图数据为空")
    return
  }

  if (!result.month) {
    console.error("后端未返回month字段")
    // 生成模拟月份数据
    result.month = Array(result.year.length).fill().map((_, i) =>
        String((i % 12) + 1).padStart(2, '0')
    )
  }

  // 提取排序后的唯一年份
  const years = [...new Set(result.year)].sort()

  // 转换热力图数据
  const heatmapData = result.year.map((year, i) => {
    const monthIndex = parseInt(result.month[i]) - 1
    return [years.indexOf(year), monthIndex, result.count[i]]
  })

  console.log("转换后热力图数据:", heatmapData)

  // 更新图表配置
  optionE.value.xAxis.data = years
  optionE.value.series[0].data = heatmapData

  // 动态设置颜色范围
  const maxCount = Math.max(...result.count)
  optionE.value.visualMap.max = maxCount > 0 ? maxCount * 1.1 : 10
}

// ================= 生命周期钩子 =================
onMounted(() => {
  initChart('boxa', optionA, getChartsA)
  initChart('boxd', optionB, getChartsB)  // 图表B现在在boxd位置
  initChart('boxc', optionC, getChartsC)
  initChart('boxb', optionD, getChartsD)  // 图表D现在在boxb位置
  initChart('boxe', optionE, getChartsE)
})
</script>

<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 左侧区域 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="9">
        <div class="chart-card">
          <div id="boxa" class="chart-wrapper"></div>
        </div>
        <!-- 图表D现在在这里（原boxb位置） -->
        <div class="chart-card">
          <div id="boxb" class="chart-wrapper"></div>
        </div>
        <div class="chart-card">
          <div id="boxc" class="chart-wrapper"></div>
        </div>
      </el-col>

      <!-- 右侧区域 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="15">
        <!-- 图表B现在在这里（原boxd位置） -->
        <div class="chart-card tall">
          <div id="boxd" class="chart-wrapper"></div>
        </div>
        <div class="chart-card x-tall">
          <div id="boxe" class="chart-wrapper"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
}

.chart-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.chart-wrapper {
  width: 100%;
  height: 100%;
}

/* 高度定义 */
.chart-card:not(.tall):not(.x-tall) {
  height: 300px;
}

.chart-card.tall {
  height: 350px;
}

.chart-card.x-tall {
  height: 440px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .chart-card:not(.tall):not(.x-tall) { height: 280px; }
  .chart-card.tall { height: 320px; }
  .chart-card.x-tall { height: 400px; }
}

@media (max-width: 992px) {
  .chart-card { margin-bottom: 15px; }
  .chart-card:not(.tall):not(.x-tall) { height: 260px; }
  .chart-card.tall { height: 300px; }
  .chart-card.x-tall { height: 380px; }
}

@media (max-width: 768px) {
  .dashboard-container { padding: 15px; }
  .chart-card {
    border-radius: 10px;
    margin-bottom: 12px;
  }
  .chart-card:not(.tall):not(.x-tall) { height: 240px; }
  .chart-card.tall { height: 280px; }
  .chart-card.x-tall { height: 350px; }
}
</style>